package com.hyl.icon.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyl.icon.common.ErrorCode;
import com.hyl.icon.constant.UserConstant;
import com.hyl.icon.exception.BusinessException;
import com.hyl.icon.exception.ThrowUtils;
import com.hyl.icon.mapper.MessageMapper;
import com.hyl.icon.model.dto.message.MessageAddRequest;
import com.hyl.icon.model.entity.Message;
import com.hyl.icon.model.entity.User;
import com.hyl.icon.service.MessageService;

import com.hyl.icon.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;


/**
 * 用户服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    private UserService userService;


    /**
     * 发送给别人的信息
     * @param userId
     * @return
     */
    @Override
    public Map<Long, List<Message>> getSendMessages(Long userId) {
        if (userId == null || userId <= 0){
            ThrowUtils.throwIf(true,ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        //1.用户必须存在
        User loginUser = userService.getById(userId);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"请登录后查看消息");
        }
        //2.禁止用户直接再见
        String userRole = loginUser.getUserRole();
        if (StringUtils.isNotBlank(userRole) && userRole.equals(UserConstant.BAN_ROLE)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"您已经被禁止使用");
        }
        //3.查找当前用户发送的消息
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",loginUser.getId());
        Page<Message> page = new Page<>(1, 20); // 第1页，每页20条记录
        queryWrapper.orderByDesc("createTime"); // 按创建时间降序排序
        List<Message> sendMessageList = this.page(page, queryWrapper).getRecords();

        //4.封装结果
        // 将 sendMessageList 转换为 Map<Long, List<Message>>，
        // 并根据 receiverId 分类，同时按照 createTime 排序
        Map<Long, List<Message>> groupedMessages = sendMessageList.stream()
                .collect(Collectors.groupingBy(
                        Message::getReceiverId,  // 根据 receiverId 分类
                        TreeMap::new,  // 使用 TreeMap 按 receiverId 排序
                        Collectors.toList()  // 将相同 receiverId 的消息收集成 List
                ))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .sorted(Comparator.comparing(Message::getCreateTime))  // 按照 createTime 排序
                                .collect(Collectors.toList())  // 收集为 List
                ));
        return groupedMessages;
    }

    @Override
    public Map<Long, List<Message>> getReceiveMessages(Long userId) {
        if (userId == null || userId <= 0){
            ThrowUtils.throwIf(true,ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        //1.用户必须存在
        User loginUser = userService.getById(userId);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"请登录后查看消息");
        }
        //2.禁止用户直接再见
        String userRole = loginUser.getUserRole();
        if (StringUtils.isNotBlank(userRole) && userRole.equals(UserConstant.BAN_ROLE)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"您已经被禁止使用");
        }
        //3.查找当前用户接受的消息
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        Page<Message> page = new Page<>(1, 20); // 第1页，每页20条记录
        queryWrapper.eq("receiverId", loginUser.getId()).orderByDesc("createTime"); // 按创建时间降序排序
        List<Message> sendMessageList = this.page(page, queryWrapper).getRecords();
        //4.封装结果
        // 将 sendMessageList 转换为 Map<Long, List<Message>>，
        // 并根据 receiverId 分类，同时按照 createTime 排序
        Map<Long, List<Message>> groupedMessages = sendMessageList.stream()
                .collect(Collectors.groupingBy(
                        Message::getUserId,  // 根据 发送id 分类
                        TreeMap::new,  // 使用 TreeMap 按 receiverId 排序
                        Collectors.toList()  // 将相同 receiverId 的消息收集成 List
                ))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .sorted(Comparator.comparing(Message::getCreateTime))  // 按照 createTime 排序
                                .collect(Collectors.toList())  // 收集为 List
                ));
        return groupedMessages;
    }

    @Override
    public Boolean sendMessage(Message message) {
        if (message == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数错误");
        }
        Long userId = message.getUserId();
        if (userId == null || userId <= 0){
            ThrowUtils.throwIf(true,ErrorCode.PARAMS_ERROR,"参数错误");
        }
        User loginUser = userService.getById(userId);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"发送方用户不存在");
        }
        Long receiverId = message.getReceiverId();
        if (receiverId == null || receiverId <= 0){
            ThrowUtils.throwIf(true,ErrorCode.PARAMS_ERROR,"参数错误");
        }
        User receiverUser = userService.getById(receiverId);
        if (receiverUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"接收方用户不存在");
        }
        //填充参数保存数据库
        message.setUserId(loginUser.getId());
        message.setSenderRole(loginUser.getUserRole());
        message.setContent(message.getContent());
        message.setReceiverId(receiverUser.getId());
        message.setReceiverRole(receiverUser.getUserRole());

        return this.save(message);
    }
}
